"""
Phase 4: Comparative Advantage Shifts
======================================
Z -> GVC position (trade_openness or gvc_proxy);
Z -> capital_intensity as proxy for manufacturing sophistication;
Demographic distance -> trade openness;
OECD/non-OECD split; income tercile heterogeneity.
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys
import warnings
warnings.filterwarnings('ignore')

PROJECT_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = PROJECT_DIR.parent
sys.path.insert(0, str(ROOT_DIR / "multilateral" / "src"))
from model import PanelGLS

DATA = PROJECT_DIR / "data" / "processed"
OUT_TABLES = PROJECT_DIR / "output" / "tables"
OUT_TABLES.mkdir(parents=True, exist_ok=True)

OECD = {
    'AUS', 'AUT', 'BEL', 'CAN', 'CHL', 'COL', 'CRI', 'CZE', 'DNK', 'EST',
    'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ISR', 'ITA', 'JPN',
    'KOR', 'LVA', 'LTU', 'LUX', 'MEX', 'NLD', 'NZL', 'NOR', 'POL', 'PRT',
    'SVK', 'SVN', 'ESP', 'SWE', 'CHE', 'TUR', 'GBR', 'USA',
}


def stars(p):
    if p < 0.01: return '***'
    if p < 0.05: return '**'
    if p < 0.1: return '*'
    return ''


def fmt(val, se, p):
    s = stars(p)
    return f"{val:.4f}{s}", f"({se:.4f})"


def run_panel_gls(df, y_var, x_vars, label):
    """Run PanelGLS and return results dict."""
    cols = [y_var] + x_vars + ['iso3', 'year']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    gls = PanelGLS()
    y = sub[y_var].values
    X = sub[x_vars].values
    try:
        gls.fit(y, X, sub['iso3'].values, sub['year'].values)
    except Exception as e:
        print(f"  {label}: GLS failed ({e}), skipping")
        return None

    result = {
        'model': label,
        'n_obs': gls.n_obs,
        'n_countries': gls.n_countries,
        'r_squared': gls.r_squared,
        'rho': gls.rho,
    }
    print(f"\n  {label} (N={gls.n_obs}, R²={gls.r_squared:.4f})")
    for i, name in enumerate(x_vars):
        sig = stars(gls.pvalues[i])
        print(f"    {name:30s} {gls.beta[i]:8.4f} ({gls.se[i]:.4f}) {sig}")
        result[f'{name}_coef'] = gls.beta[i]
        result[f'{name}_se'] = gls.se[i]
        result[f'{name}_p'] = gls.pvalues[i]

    return result


def write_table(results, filename, title):
    """Write regression results as markdown table."""
    if not results:
        return

    lines = [f"# {title}\n"]

    all_vars = []
    for r in results:
        for k in r:
            if k.endswith('_coef'):
                vname = k.replace('_coef', '')
                if vname not in all_vars:
                    all_vars.append(vname)

    model_labels = [r['model'] for r in results]
    header = "| Variable | " + " | ".join(model_labels) + " |"
    sep = "|:---|" + "|".join(["---:" for _ in results]) + "|"
    lines.append(header)
    lines.append(sep)

    for var in all_vars:
        coef_row = f"| {var} |"
        se_row = "| |"
        for r in results:
            if f'{var}_coef' in r:
                c, s = fmt(r[f'{var}_coef'], r[f'{var}_se'], r[f'{var}_p'])
                coef_row += f" {c} |"
                se_row += f" {s} |"
            else:
                coef_row += " |"
                se_row += " |"
        lines.append(coef_row)
        lines.append(se_row)

    lines.append("|:---|" + "|".join(["---:" for _ in results]) + "|")
    n_row = "| N |"
    r2_row = "| R² |"
    nc_row = "| Countries |"
    for r in results:
        n_row += f" {r['n_obs']} |"
        r2_row += f" {r['r_squared']:.4f} |"
        nc_row += f" {r['n_countries']} |"
    lines.append(n_row)
    lines.append(r2_row)
    lines.append(nc_row)

    lines.append("\n*Panel GLS with country and year fixed effects. "
                 "Standard errors in parentheses.*")
    lines.append("*\\*p<0.1, \\*\\*p<0.05, \\*\\*\\*p<0.01*")

    path = OUT_TABLES / filename
    path.write_text('\n'.join(lines))
    print(f"\n  Saved: {path}")


# ── 1. Demographics → GVC Position ─────────────────────────────────

def gvc_demographics(df):
    """Demographics → GVC position proxy (trade_openness or gvc_proxy)."""
    print("\n" + "=" * 60)
    print("1. DEMOGRAPHICS → GVC POSITION")
    print("=" * 60)

    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']

    results = []

    # Determine GVC proxy variable
    gvc_var = 'gvc_proxy' if 'gvc_proxy' in df.columns else 'trade_openness'
    print(f"  GVC proxy variable: {gvc_var}")

    # M1: Z → GVC proxy
    r = run_panel_gls(df, gvc_var,
                      ['Z_1', 'Z_2', 'Z_3'],
                      'M1: Z only')
    if r: results.append(r)

    # M2: Z + controls → GVC proxy
    r = run_panel_gls(df, gvc_var,
                      ['Z_1', 'Z_2', 'Z_3'] + controls,
                      'M2: Z + Controls')
    if r: results.append(r)

    # M3: Age decomposition → GVC proxy
    r = run_panel_gls(df, gvc_var,
                      ['old_dep', 'youth_dep'] + controls,
                      'M3: Age Decomp')
    if r: results.append(r)

    # M4: Z → capital_intensity (manufacturing sophistication)
    if 'capital_intensity' in df.columns:
        r = run_panel_gls(df, 'capital_intensity',
                          ['Z_1', 'Z_2', 'Z_3'] + controls,
                          'M4: Z → Cap Intensity')
        if r: results.append(r)

    # M5: Z + working_age_share → GVC proxy
    if 'working_age_share' in df.columns:
        r = run_panel_gls(df, gvc_var,
                          ['Z_1', 'Z_2', 'Z_3', 'working_age_share'] + controls,
                          'M5: Z + WA Share')
        if r: results.append(r)

    write_table(results, "gvc_demographics.md",
                "Demographics and GVC Position")


# ── 2. Demographic Distance → Trade ────────────────────────────────

def demo_distance_trade(df):
    """Demographic distance to global mean → trade openness."""
    print("\n" + "=" * 60)
    print("2. DEMOGRAPHIC DISTANCE → TRADE OPENNESS")
    print("=" * 60)

    # Compute demographic distance to year mean
    df = df.copy()
    year_means = df.groupby('year')['Z_1'].transform('mean')
    df['demo_distance_to_mean'] = np.abs(df['Z_1'] - year_means)

    print(f"  demo_distance_to_mean: mean={df['demo_distance_to_mean'].mean():.3f}, "
          f"std={df['demo_distance_to_mean'].std():.3f}")

    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']

    results = []

    # M1: Distance → trade openness
    r = run_panel_gls(df, 'trade_openness',
                      ['demo_distance_to_mean'],
                      'M1: Distance only')
    if r: results.append(r)

    # M2: Distance + controls → trade openness
    r = run_panel_gls(df, 'trade_openness',
                      ['demo_distance_to_mean'] + controls,
                      'M2: + Controls')
    if r: results.append(r)

    # M3: Distance + GDP per capita
    if 'gdp_pc_ppp' in df.columns:
        r = run_panel_gls(df, 'trade_openness',
                          ['demo_distance_to_mean', 'gdp_pc_ppp'] + controls,
                          'M3: + GDP/capita')
        if r: results.append(r)

    # M4: Distance → CA/GDP (does demo distance drive CA?)
    r = run_panel_gls(df, 'ca_gdp',
                      ['demo_distance_to_mean'] + controls,
                      'M4: Distance → CA')
    if r: results.append(r)

    write_table(results, "demo_distance_trade.md",
                "Demographic Distance and Trade Openness")

    return df


# ── 3. Subsamples: OECD/Non-OECD + Income Terciles ─────────────────

def comparative_adv_subsamples(df):
    """OECD/non-OECD and income tercile heterogeneity for GVC regressions."""
    print("\n" + "=" * 60)
    print("3. COMPARATIVE ADVANTAGE SUBSAMPLES")
    print("=" * 60)

    df = df.copy()
    df['is_oecd'] = df['iso3'].isin(OECD).astype(int)
    oecd_df = df[df['is_oecd'] == 1].copy()
    non_oecd_df = df[df['is_oecd'] == 0].copy()

    print(f"  OECD: {oecd_df['iso3'].nunique()} countries, {len(oecd_df)} obs")
    print(f"  Non-OECD: {non_oecd_df['iso3'].nunique()} countries, {len(non_oecd_df)} obs")

    gvc_var = 'gvc_proxy' if 'gvc_proxy' in df.columns else 'trade_openness'
    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']
    x_vars = ['Z_1', 'Z_2', 'Z_3'] + controls

    results = []

    # OECD / Non-OECD split
    for sub_df, label in [(df, 'Full'), (oecd_df, 'OECD'), (non_oecd_df, 'Non-OECD')]:
        r = run_panel_gls(sub_df, gvc_var, x_vars, f'{label}')
        if r: results.append(r)

    # Income terciles
    if 'gdp_pc_ppp' in df.columns:
        df['income_tercile'] = pd.qcut(
            df['gdp_pc_ppp'].dropna(), 3,
            labels=['Low', 'Mid', 'High']
        ).reindex(df.index)

        for tercile in ['Low', 'Mid', 'High']:
            sub = df[df['income_tercile'] == tercile].copy()
            r = run_panel_gls(sub, gvc_var, x_vars, f'Inc: {tercile}')
            if r: results.append(r)

    write_table(results, "comparative_adv_subsamples.md",
                "Comparative Advantage: OECD/Non-OECD and Income Terciles")


# ── Main ────────────────────────────────────────────────────────────

def main():
    print("=" * 70)
    print("PHASE 4: COMPARATIVE ADVANTAGE SHIFTS")
    print("=" * 70)

    df = pd.read_csv(DATA / "automation_panel.csv")
    print(f"Panel: {len(df)} obs, {df['iso3'].nunique()} countries")
    print(f"Columns: {list(df.columns)}")

    # 1. Demographics → GVC position
    gvc_demographics(df)

    # 2. Demographic distance → trade
    df = demo_distance_trade(df)

    # 3. Subsamples
    comparative_adv_subsamples(df)

    print("\n" + "=" * 70)
    print("PHASE 4 COMPLETE")
    print("=" * 70)


if __name__ == '__main__':
    main()
